// 文件：src/app/graph/page.tsx
"use client";
import { useState } from "react";

export default function GraphPage() {
  const [q, setQ] = useState("");
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const run = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/graph", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question: q || "公司报销政策？", retriever: "hybrid" }),
      });
      console.log(res)
      // 检查响应状态
      if (!res.ok) {
        const errorData = await res.json().catch(() => ({ message: `HTTP ${res.status} 错误` }));
        setData({ error: errorData.message || errorData, stack: errorData.stack });
        setLoading(false);
        return;
      }
      
      const json = await res.json();
      if (json.ok) {
        setData(json.data);
      } else {
        setData({ error: json.message || "未知错误", stack: json.stack });
      }
    } catch (error: any) {
      console.error("请求失败:", error);
      setData({ error: error?.message || "网络请求失败", details: String(error) });
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="max-w-3xl mx-auto p-4 space-y-4">
      <h1 className="text-2xl font-bold">LangGraph 状态图查看器</h1>
      <div className="flex gap-2">
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="输入问题" className="flex-1 border rounded px-3 py-2" />
        <button onClick={run} className="px-4 py-2 bg-blue-600 text-white rounded" disabled={loading}>{loading ? "运行中..." : "运行"}</button>
      </div>
      {data && (
        <section className="space-y-2">
          <h2 className="font-semibold">{data.error ? "❌ 错误信息" : "✅ 执行结果"}</h2>
          {data.error && (
            <div className="bg-red-50 border border-red-200 rounded p-3 mb-2">
              <p className="text-red-800 font-semibold">错误: {data.error}</p>
              {data.stack && (
                <details className="mt-2">
                  <summary className="text-red-600 cursor-pointer text-sm">查看堆栈信息</summary>
                  <pre className="mt-2 text-xs text-red-700 whitespace-pre-wrap">{data.stack}</pre>
                </details>
              )}
            </div>
          )}
          <pre className="whitespace-pre-wrap break-words text-sm bg-gray-50 p-3 rounded border">{JSON.stringify(data, null, 2)}</pre>
        </section>
      )}
    </main>
  );
}
